﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GsifWeb4.Models;
using GsifWeb4.ViewModels;

namespace GsifWeb4.Controllers
{
    public class PlayerController : Controller
    {
        private gsifdbEntities gsifDB = new gsifdbEntities();

        #region Player
        //
        // GET: /Player/

        public ActionResult Index()
        {
            return View(gsifDB.laget_gsif.ToList());
        }

        //
        // GET: /Player/ShowPlayer/351
        // Visar en spelare med matcher mm
        public ActionResult ShowPlayer(int id)
        {
            var dbPlayer = (from players in gsifDB.laget_gsif
                            where players.ID == id
                            select players).Single();

            var matches = from stat in gsifDB.statistik_gsif
                          join match in gsifDB.match_gsif on stat.StId equals match.MaId
                          where stat.SpId == id && stat.StType == StatisticType.Match.DbValue
                          select new { Statistics = stat, match.MaId, match.Datum, match.Lag, match.Motstandare, match.Omgang, match.Resultat, match.Typ, match.Tid };

            int totalManOfMatch = matches.Count(m => m.Statistics.ManOfMatch != null && m.Statistics.ManOfMatch == "on");

            PlayerViewModel player = new PlayerViewModel();
            player.Image = dbPlayer.Bild;
            player.Name = dbPlayer.FNamn + " " + dbPlayer.ENamn;
            //player.Position = Common.Position.GetPositionText(Convert.ToInt32(dbPlayer.Position));
            player.Position = Statuses.GetTextFromDbValue(Position.AllStatuses, dbPlayer.Position);
            player.Born = dbPlayer.Fodd;
            player.Length = dbPlayer.Langd;
            player.Weight = dbPlayer.Vikt;
            player.MotherClub = dbPlayer.Klubb;
            player.Motto = dbPlayer.Motto;
            player.ManOfTheMatch = totalManOfMatch;

            // Set default values. Theese will be incremented while looping the matches
            player.TotalGoalKeeper = 0;
            player.TotalDefender = 0;
            player.TotalMidfielder = 0;
            player.TotalForward = 0;
            player.TotalSubstitute = 0;

            // Add all matches
            player.Matches = new List<MatchWithPersonalInfo>();

            int herrAGames = 0;
            int herrCGames = 0;
            int damAGames = 0;
            int damBGames = 0;

            foreach (var match in matches)
            {
                if (Common.StatisticMatchPosition.IsPosition((int)match.Statistics.Typ, Common.StatisticMatchPosition.GoalKeeper))
                    player.TotalGoalKeeper++;
                else if (Common.StatisticMatchPosition.IsPosition((int)match.Statistics.Typ, Common.StatisticMatchPosition.Defender))
                    player.TotalDefender++;
                else if (Common.StatisticMatchPosition.IsPosition((int)match.Statistics.Typ, Common.StatisticMatchPosition.Midfield))
                    player.TotalMidfielder++;
                else if (Common.StatisticMatchPosition.IsPosition((int)match.Statistics.Typ, Common.StatisticMatchPosition.Forward))
                    player.TotalForward++;
                else if (Common.StatisticMatchPosition.IsPosition((int)match.Statistics.Typ, Common.StatisticMatchPosition.Substitute))
                    player.TotalSubstitute++;


                StatusValue team = GsifWeb4.Team.GetStatusFromDbValue(GsifWeb4.Team.AllTeams, match.Lag);
                if (team.DbValue == GsifWeb4.Team.MenA.DbValue)
                    herrAGames++;
                else if (team.DbValue == GsifWeb4.Team.MenC.DbValue)
                    herrCGames++;
                else if (team.DbValue == GsifWeb4.Team.WomenA.DbValue)
                    damAGames++;
                else if (team.DbValue == GsifWeb4.Team.WomenB.DbValue)
                    damBGames++;

                MatchWithPersonalInfo personalMatchStat = new MatchWithPersonalInfo();

                personalMatchStat.Id = (int)match.MaId;

                if (match.Statistics.Assist.HasValue)
                    personalMatchStat.Assists = (int)match.Statistics.Assist.Value;

                if (match.Statistics.Gula.HasValue)
                    personalMatchStat.YellowCard = (int)match.Statistics.Gula.Value;

                personalMatchStat.Team = match.Statistics.Lag;

                if (match.Statistics.Mal.HasValue)
                    personalMatchStat.Goals = (int)match.Statistics.Mal.Value;

                personalMatchStat.ManOfTheMatch = match.Statistics.ManOfMatch;

                if (match.Statistics.Roda.HasValue)
                    personalMatchStat.RedCard = (int)match.Statistics.Roda.Value;

                personalMatchStat.Opponent = match.Motstandare;

                if (MatchType.League.IsDbValue(match.Typ))
                    personalMatchStat.Round = "Omgång " + match.Omgang;
                else
                    personalMatchStat.Round = MatchType.GetStatusFromDbValue(MatchType.AllStatuses, match.Typ).Text;

                personalMatchStat.Result = match.Resultat;

                if (match.Datum.HasValue)
                {
                    personalMatchStat.Year = match.Datum.Value.Year;
                    personalMatchStat.Date = match.Datum.Value;
                }

                player.Matches.Add(personalMatchStat);
            }

            string text = "";
            if (herrAGames > 0)
                text += (text == "" ? "" : " ") + "Herr A-lag: " + herrAGames;
            if (herrCGames > 0)
                text += (text == "" ? "" : " ") + "Herr C-lag: " + herrCGames;
            if (damAGames > 0)
                text += (text == "" ? "" : " ") + "Dam A-lag: " + damAGames;
            if (damBGames > 0)
                text += (text == "" ? "" : " ") + "Dam B-lag: " + damBGames;

            player.TotalGames = matches.Count().ToString() + " (" + text + ")";

            return View("ShowPlayer", player);
        }

        //
        // GET: /Player/Details/5

        public ActionResult Details(int id = 0)
        {
            laget_gsif laget_gsif = gsifDB.laget_gsif.Single(l => l.ID == id);
            if (laget_gsif == null)
            {
                return HttpNotFound();
            }
            return View(laget_gsif);
        }

        //
        // GET: /Player/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Player/Create

        [HttpPost]
        public ActionResult Create(laget_gsif laget_gsif)
        {
            if (ModelState.IsValid)
            {
                gsifDB.laget_gsif.AddObject(laget_gsif);
                gsifDB.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(laget_gsif);
        }

        //
        // GET: /Player/Edit/5

        public ActionResult Edit(int id = 0)
        {
            laget_gsif laget_gsif = gsifDB.laget_gsif.Single(l => l.ID == id);
            if (laget_gsif == null)
            {
                return HttpNotFound();
            }
            return View(laget_gsif);
        }

        //
        // POST: /Player/Edit/5

        [HttpPost]
        public ActionResult Edit(laget_gsif laget_gsif)
        {
            if (ModelState.IsValid)
            {
                gsifDB.laget_gsif.Attach(laget_gsif);
                gsifDB.ObjectStateManager.ChangeObjectState(laget_gsif, EntityState.Modified);
                gsifDB.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(laget_gsif);
        }

        //
        // GET: /Player/Delete/5

        public ActionResult Delete(int id = 0)
        {
            laget_gsif laget_gsif = gsifDB.laget_gsif.Single(l => l.ID == id);
            if (laget_gsif == null)
            {
                return HttpNotFound();
            }
            return View(laget_gsif);
        }

        //
        // POST: /Player/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            laget_gsif laget_gsif = gsifDB.laget_gsif.Single(l => l.ID == id);
            gsifDB.laget_gsif.DeleteObject(laget_gsif);
            gsifDB.SaveChanges();
            return RedirectToAction("Index");
        }
        #endregion

        public ActionResult UpdateProfile(int id)
        {
            var dbPlayer = (from players in gsifDB.laget_gsif
                            where players.ID == id
                            select players).Single();

            return View(dbPlayer);
        }

        [HttpPost]
        public ActionResult UpdateProfile(int id, FormCollection collection)
        {
            var dbPlayer = (from players in gsifDB.laget_gsif
                            where players.ID == id
                            select players).Single();

            if (dbPlayer == null)
                return View("PlayerNotFound");

            string newUserName = collection["Anvandarnamn"];
            string oldPassword = collection["OldPassword"];
            string newPassword = collection["NewPassword"];
            string repeatNewPassword = collection["RepeatNewPassword"];

            string setNewPassword = null;

            if (!string.IsNullOrEmpty(newPassword))
            {
                // Användaren vill byta lösenord

                if (string.IsNullOrEmpty(oldPassword))
                {
                    // Nytt lösenord angett men inget gammalt
                    ModelState.AddModelError("OldPassword", "Du måste ange det gamla lösenordet för att kunna byta lösenord.");
                    return View(dbPlayer);
                }

                if (!UserManagement.ValidateUser(dbPlayer.Anvandarnamn, oldPassword, gsifDB))
                {
                    // Det gamla lösenordet stämmer inte med DB
                    ModelState.AddModelError("OldPassword", "Gammalt lösenord stämmer inte.");
                    return View(dbPlayer);
                }

                if (newPassword != repeatNewPassword)
                {
                    // Det gamla lösenordet stämmer inte med DB
                    ModelState.AddModelError("NewPassword", "Det nya lösenordet stämmer inte med det repeterade.");
                    ModelState.AddModelError("RepeatNewPassword", "Det nya lösenordet stämmer inte med det repeterade.");
                    return View(dbPlayer);
                }

                if (!UserManagement.PasswordStrengthOK(newPassword))
                {
                    ModelState.AddModelError("NewPassword", "Lösenordet måste bestå av minst 5 tecken");
                    return View(dbPlayer);
                }

                // Lösenord ok att ändras
                setNewPassword = Crypto.GetEncryptedValue(newPassword);
            }

            bool needLogInAgain = false;
            if (dbPlayer.Anvandarnamn != newUserName)
            {
                // Kontrollera att användarnamnet ej är upptaget
                var existingUserName = (from players in gsifDB.laget_gsif
                                        where players.Anvandarnamn == newUserName
                                        select players).FirstOrDefault();

                if (existingUserName != null)
                {
                    ModelState.AddModelError("Anvandarnamn", "Det valda användarnamnet är redan upptaget. Välj annat användarnamn.");
                    return View(dbPlayer);
                }

                needLogInAgain = true;
            }

            TryUpdateModel(dbPlayer);

            // Specialhantering kring lösenord. Sätt nytt lösenord om användaren gjorde det
            if (setNewPassword != null)
                dbPlayer.Password = setNewPassword;

            gsifDB.SaveChanges();
            ViewBag.InfoText = "Uppdateringen lyckades. " + (needLogInAgain ? "Du behöver logga ut och sedan logga in igen." : "");

            //ViewData["InfoText"] = "Uppdateringen lyckades. " + (needLogInAgain ? "Du behöver logga ut och sedan logga in igen." : "");
            return View(dbPlayer);
        }


        #region Team
        public ActionResult Team(string team)
        {
            List<laget_gsif> players = (from player in gsifDB.laget_gsif
                                        where player.Lag == team && player.Inaktiv != InActivePlayer.InActive.DbValue
                                        select player).ToList();

            TeamViewModel teamViewModel = new TeamViewModel();

            teamViewModel.Coaches = players.Where(p => Position.Coach.IsDbValue(p.Position)).ToList();
            teamViewModel.GoalKeepers = players.Where(p => Position.GoalKeeper.IsDbValue(p.Position)).ToList();
            teamViewModel.Defenders = players.Where(p => Position.Defender.IsDbValue(p.Position)).ToList();
            teamViewModel.Midfielders = players.Where(p => Position.Midfielder.IsDbValue(p.Position)).ToList();
            teamViewModel.Forwards = players.Where(p => Position.Forward.IsDbValue(p.Position)).ToList();

            ViewBag.TeamName = Statuses.GetTextFromDbValue(GsifWeb4.Team.AllTeams, team);
            return View("Team", teamViewModel);
        }

        #endregion

        protected override void Dispose(bool disposing)
        {
            gsifDB.Dispose();
            base.Dispose(disposing);
        }
    }
}